import time

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMessageBox

from common.common import Common
from data_manage.udp_manager import UdpManager
from data_manage.work_thread import WorkThread


class ShowTabUdp:
    def __init__(self, ui, ptr):
        self.ui = ui
        self.open = True
        self.recv = True
        self.udp_socket = None
        self.thread = None
        self.ptr = ptr
        pass

    def init_ui(self):
        png = Common.get_resource_path() + "提示.png"
        self.ui.toolButton_12.setIcon(QIcon(png))
        png = Common.get_resource_path() + "IP.png"
        self.ui.toolButton_10.setIcon(QIcon(png))
        png = Common.get_resource_path() + "port.png"
        self.ui.toolButton_11.setIcon(QIcon(png))

        self.ui.lineEdit_udp_ip.setPlaceholderText("例：192.168.1.1")
        self.ui.lineEdit_udp_port.setPlaceholderText("例：3333")

        self.ui.pushButton_udp_recv.setEnabled(False)
        self.init_connect()
        pass

    def init_connect(self):
        self.ui.pushButton_udp_init.clicked.connect(lambda: self.btn_udp_init_clicked("on_udp_init_click"))
        self.ui.pushButton_udp_recv.clicked.connect(lambda: self.btn_udp_recv_clicked("on_udp_recv_click"))
        pass

    @staticmethod
    def is_valid_ip(ip: str):
        # 检查 IP 地址格式
        parts = ip.split(".")
        if len(parts) != 4:
            return False
        # 检查每个部分是否为数字且在 0-255 之间
        for part in parts:
            if not part.isdigit():
                return False
            num = int(part)
            if num < 0 or num > 255:
                return False
        return True

    def btn_udp_init_clicked(self, info):
        print(info)
        ip_str = self.ui.lineEdit_udp_ip.text()
        port_str = self.ui.lineEdit_udp_port.text()
        print(ip_str, port_str)
        if not ip_str or not port_str:
            QMessageBox.warning(self.ptr, "Error", "输入框内无数据！", QMessageBox.Cancel)
            return
        if not ShowTabUdp.is_valid_ip(ip_str):
            QMessageBox.warning(self.ptr, "Error", "不符合IP地址格式，例：192.168.1.1", QMessageBox.Cancel)
            return
        port_int = int(port_str)
        if port_int <= 0 or port_int >= 65535:
            QMessageBox.warning(self.ptr, "Error", "端口号超出范围0-65535", QMessageBox.Cancel)
            return
        if self.open:
            self.udp_socket = UdpManager(ip_str, port_int)
            if self.udp_socket.get_socket() is None:
                QMessageBox.warning(self.ptr, "Error", "别试了，udp初始化失败！", QMessageBox.Cancel)
                return
            else:
                Common().set_udp_socket(self.udp_socket)
                Common().set_udp_para(ip_str, port_int)
                self.ui.pushButton_udp_init.setText("关闭UDP")
                # self.udp_socket.send_udp_data(ip_str, port_int, "message")
                self.open = False
                self.ui.pushButton_udp_recv.setEnabled(True)
        else:
            if self.udp_socket is not None:
                self.udp_socket.udp_close()
            self.ui.pushButton_udp_init.setText("初始化")
            self.open = True
            self.ui.pushButton_init_recv.setEnabled(False)
        pass

    def btn_udp_recv_clicked(self, info):
        print(info)
        if self.recv:
            # begin incoming inspection
            Common().send_data(0x224, [0xA5, 0x01, 0x20, 0x01, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # Common().send_data(0x224, [0xA5, 0x01, 0x21, 0x02, 0xE8, 0x03, 0x00, 0xA5])
            #self.can_bus.send_data(0x224, [0xA5, 0x01, 0x20, 0x01, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # # receive motor drive & increase
            # self.can_bus.send_data(0x226, [0xA5, 0x01, 0x50, 0x01, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # # receive motor mower
            # self.can_bus.send_data(0x228, [0xA5, 0x01, 0x70, 0x01, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # # receive sensor IMU & rain & ultrasonic
            # self.can_bus.send_data(0x22A, [0xA5, 0x01, 0x90, 0x01, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # # receive sensor light & current & battery & key & lift
            # self.can_bus.send_data(0x22C, [0xA5, 0x01, 0xA0, 0x01, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            self.ui.pushButton_udp_recv.setText("停止接收")
            self.recv = False
            Common().set_thread_recv(True)
            self.start_thread()
        else:
            # self.can_bus.send_data(0x226, [0xA5, 0x01, 0x50, 0x00, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # self.can_bus.send_data(0x228, [0xA5, 0x01, 0x70, 0x00, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # self.can_bus.send_data(0x22A, [0xA5, 0x01, 0x90, 0x00, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # self.can_bus.send_data(0x22C, [0xA5, 0x01, 0xA0, 0x00, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            # self.can_bus.send_data(0x224, [0xA5, 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0xA5])
            Common().send_data(0x224, [0xA5, 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0xA5])
            # time.sleep(0.08)
            self.ui.pushButton_udp_recv.setText("接收数据")
            self.recv = True
            Common().set_thread_recv(False)
        pass

    def start_thread(self):
        self.thread = WorkThread(self.udp_socket)
        #self.thread.signal_update.connect(Common().get_show_tab_window().update_recv_data)
        self.thread.start()

